package com;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.netty.client.ClientProxy;
import com.netty.common.bean.product.Product;
import com.netty.discovery.ServiceDiscovery;
import com.netty.future.RPCFuture;
import com.netty.product.ProductService;
import com.netty.proxy.IAsyncObjectProxy;

@Configuration
public class Application {
	
	
	private ServiceDiscovery getServiceDiscovery(){
		String registryAddress = "127.0.0.1:2181";
		ServiceDiscovery discovery = new ServiceDiscovery(registryAddress);
		return discovery;
	}
	
	private ClientProxy getProxy() {
		ClientProxy proxy = new ClientProxy(getServiceDiscovery());
		return proxy;
	}
	
	@Bean
	public ProductService getProductService(){
		return getProxy().create(ProductService.class);
	}
	
	@Bean("asyncProductService")
	public IAsyncObjectProxy getSynProductService(){
		IAsyncObjectProxy proxy = getProxy().createAsync(ProductService.class);
		return proxy;
		//return getProxy().createAsync(ProductService.class);
	}
	
	public static void main(String[] args) {
		AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Application.class);
		ProductService productService = ctx.getBean(ProductService.class);
		int productid = 100866;
		//String result = productService.getProduct(productid);
		//System.out.println(result);
		IAsyncObjectProxy asyncProductService = ctx.getBean("asyncProductService",IAsyncObjectProxy.class);
		RPCFuture future = asyncProductService.call("getProduct", productid);
		try {
			Object obj = future.get(3000, TimeUnit.MILLISECONDS);
			Product product = (Product) obj;
			System.out.println(product.toString());
		} catch (InterruptedException | ExecutionException | TimeoutException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
